import { boot } from "quasar/wrappers";
import { uuidv4 } from "src/utility/StringUtil.js";
import axios from "axios";

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({
  baseURL:
    process.env.NODE_ENV === "production"
      ? "/api/v1"
      : "http://127.0.0.1:5000/api/v1",
});
const basePath =
  process.env.NODE_ENV === "production" ? "" : "http://127.0.0.1:5000";

const InitSessionId = () => {
  let sessionId = localStorage.getItem("sessionId");
  if (!sessionId) {
    sessionId = uuidv4();
    localStorage.setItem("sessionId", sessionId);
  }
  api.defaults.headers.common["Session-Id"] = sessionId;
  console.log("sessionId", sessionId);
};

InitSessionId();

const session = {
  get: async function (key) {
    try {
      return (await api.get("/session/?key=" + encodeURIComponent(key))).data
        .data;
    } catch (error) {
      console.log("get session error", error);
      return null;
    }
  },
  set: async function (key, value) {
    try {
      await api.post("/session/", { key, value });
    } catch (error) {
      console.log("set session error", error);
    }
  },
  remove: async function (key) {
    try {
      await api.post("/session/_remove", { key });
    } catch (error) {
      console.log("remove session error", error);
    }
  },
  clear: async function () {
    try {
      await api.delete("/session/_all");
    } catch (error) {
      console.log("clear session error", error);
    }
  },
};

const redirect_url = window.location.origin + "/#/";
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 查看响应错误
    if (error.response && error.response.status === 403) {
      // 检测到403状态码时，执行特定操作
      console.log("403 Forbidden: 登录状态失效");
      localStorage.clear();
      InitSessionId();
      api.defaults.headers.common["Session-Id"] = sessionId;
      if (window.location.href !== redirect_url) {
        session.clear().then(() => {
          session.set("last_href", window.location.href);
          window.location.href = redirect_url;
        });
      }
    }

    // 返回错误信息，以便于后续的处理
    return Promise.reject(error);
  },
);

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api;
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API

  app.config.globalProperties.$session = session;
});

export { api, session, basePath };
